/*
 * @Author: jiutian
 * @Date: 2023-02-01 09:22:48
 * @LastEditTime: 2023-03-20 16:36:18
 * @LastEditors:  
 */
import axios from "axios";
import modules from "./";
import { checkObjKey } from "@utils";
import { ElLoading } from "element-plus";
// import { useRouter } from "vue-router";
import $router from "@/router";
// const $router = useRouter();
const request: object = {};

let apiUrl: string = import.meta.env.DEV ? "/api" : "/";
// let apiUrl: string = import.meta.env.DEV ? "/api" : "";

// 挂在接口
let server = axios.create({
  baseURL: apiUrl,
  timeout: 10000,
});

interface serverOption {
  method: string;
  url: string;
  data?: object;
  params?: object;
}

Object.keys(modules).forEach((key: string) => {
  modules[key].forEach((item: any) => {
    request[`${key}/${item.name}`] = (args: any) => {
      return new Promise((resolve, reject) => {
        let option: serverOption = {
          method: item.method || "get",
          url: item.path,
        };
        if (item.data) {
          option.data = checkObjKey(item.data, args.data || {});
        }

        if (item.params) {
          option.params = checkObjKey(item.params, args.params || {});
        }

        server(option)
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      }).catch((err) => {
        console.log(err);
      });
    };
  });
});

server.interceptors.request.use(
  (config: any) => {
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

server.interceptors.response.use(
  (res: any) => {
    if (res.data.code == 402) {
      localStorage.removeItem("token");
      ElLoading.service();
      setTimeout(() => {
        $router.replace({
          name: "login",
        });
      }, 300);
    }
    return res;
  },
  (err) => {
    return Promise.reject(err);
  }
);

export default request;
